package com.gt.quality.config.handler;


import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.gt.quality.config.utils.LoginHelper;
import com.gt.quality.config.utils.LoginUser;
import com.gt.quality.base.pojo.CommonTableInfo;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

/**
 * @description: Mybatis -plus  自动填充
 * @author: makeJava
 * @since JDK21
 **/
@Slf4j
@Component
public class MyMetaObjectHandler implements MetaObjectHandler {

    /**
     * 注意填充的字段必须要加注解 参考@TableField(value = "create_dept", fill = FieldFill.INSERT)
     *
     * @param metaObject 元对象
     */

    @Override
    public void insertFill(MetaObject metaObject) {
        log.info("start insert fill ...." );
        if (ObjectUtil.isNotNull(metaObject) && metaObject.getOriginalObject() instanceof CommonTableInfo baseEntity) {
            // 获取当前时间作为创建时间和更新时间，如果创建时间不为空，则使用创建时间，否则使用当前时间
            LocalDateTime current = ObjectUtil.isNotNull(baseEntity.getCreateTime())
                    ? baseEntity.getCreateTime() : LocalDateTime.now();
            baseEntity.setCreateTime(current);
            baseEntity.setUpdateTime(current);
            baseEntity.setDelFlag(true);
            // 如果创建人为空，则填充当前登录用户的信息
            if (ObjectUtil.isNull(baseEntity.getCreateBy())) {
                LoginUser loginUser = getLoginUser();
                if (ObjectUtil.isNotNull(loginUser)) {
                    Long userId = loginUser.getUserId();
                    // 填充创建人、更新人和创建部门信息
                    baseEntity.setCreateBy(userId);
                    baseEntity.setUpdateBy(userId);
                    baseEntity.setCreateDept(ObjectUtil.isNotNull(baseEntity.getCreateDept())
                            ? baseEntity.getCreateDept() : loginUser.getDeptId());
                }
            }
            this.strictInsertFill(metaObject, "createBy", Long.class, baseEntity.getCreateBy()); 
            this.strictInsertFill(metaObject, "updateBy", Long.class, baseEntity.getUpdateBy()); 
            this.strictInsertFill(metaObject, "createDept", Long.class, baseEntity.getCreateDept()); 
        }
        // 或者
        this.strictInsertFill(metaObject, "createTime", LocalDateTime::now, LocalDateTime.class); 
        this.strictInsertFill(metaObject, "updateTime", LocalDateTime::now, LocalDateTime.class); 
        this.strictInsertFill(metaObject, "tenant_id", String.class, "000000" ); 
    }

    /**
     * 更新时候填充的字段 也必须加注解
     *
     * @param metaObject 元对象
     */
    @Override
    public void updateFill(MetaObject metaObject) {
        log.info("start update fill ...." );
        if (ObjectUtil.isNotNull(metaObject) && metaObject.getOriginalObject() instanceof CommonTableInfo baseEntity) {
            // 获取当前时间作为更新时间，无论原始对象中的更新时间是否为空都填充
            LocalDateTime current = LocalDateTime.now();
            baseEntity.setUpdateTime(current);
            // 获取当前登录用户的ID，并填充更新人信息
            Long userId = LoginHelper.getUserId();
            if (ObjectUtil.isNotNull(userId)) {
                baseEntity.setUpdateBy(userId);
            }
            this.strictInsertFill(metaObject, "updateBy", Long.class, baseEntity.getUpdateBy()); 
        }
        this.strictUpdateFill(metaObject, "updateTime", LocalDateTime::now, LocalDateTime.class);
    }

    /**
     * 获取当前登录用户信息
     *
     * @return 当前登录用户的信息，如果用户未登录则返回 null
     */
    private LoginUser getLoginUser() {
        LoginUser loginUser;
        try {
            loginUser = LoginHelper.getLoginUser();
        } catch (Exception e) {
            log.warn("自动注入警告 => 用户未登录" );
            return null;
        }
        return loginUser;
    }
}